import moment from 'moment';

function execFunc(funcStr, context) {
  const funcBody = processFunc(funcStr);
  let expInstance = new createExpInstance();
  let expValue = expInstance.getValue(funcBody, context);
  return expValue;
}

function processFunc(funcStr) {
  return funcStr.replace(/{{([^}]+)}}/g, (_, expression) => processVariable(expression));
}

function processVariable(expression) {
  const precessedExpression = expression.replace(/(now\s*([+-]\d+[dMwy])?)/g, (_, dateExpression) =>
    processDateStr(dateExpression)
  );
  return precessedExpression;
}

const unitMap = {
  d: 'days',
  W: 'weeks',
  M: 'months',
  y: 'years'
};

function processDateStr(expression) {
  const date = moment();
  const added = expression.match(/now\s*([+-]\s*\d+[dMwy])/)?.[1];
  if (added) {
    const [_, sign, num, unit] = added.match(/([+-])\s*(\d+)([dMwy])/);
    date.add({[unitMap[unit]]: Number(`${sign}${num}`)});
  }
  return `(new Date('${date.format('YYYY-MM-DD HH:mm:ss')}'))`;
}

/** execFunc 相关 */
function createExpInstance() {
}

createExpInstance.prototype.getValue = function (exp, context) {
  if (!exp) return;
  try {
    let func = new Function("args", "getAction", "deleteAction", "putAction", "postAction", "httpAction","downFile", "moment", "uuid", "ComUtils", "store", "callback", exp);
    let currentFunc = func.bind(context);
    return currentFunc;
  } catch (err) {
    //console.log(err);
  }
};

export {execFunc};
